<template>
  <div class="article-page">
    <div
      v-for="item in articles"
      :key="item.id"
      @click="$router.push(`/detail/${item.id}`)"
      class="article-item">
      <div class="head">
         <!-- <img src="@/assets/upload/test.jpg" alt="" /> -->
        <!-- <img :src="item.creatorAvatar" alt="" /> -->
        <img :src="getCreatorAvatarUrl(item.creatorAvatar)" alt="" />
        <div class="con">
          <p class="title">{{ item.stem }}</p>
          <p class="other">{{ item.creatorName }} | {{ formatDateTime(item.createdAt) }}</p>
        </div>
      </div>
      <div class="body">
        {{ item.content }}
      </div>
      <div class="foot">
        点赞 {{ item.likeCount }} | 浏览 {{ item.views }} |  评论 {{ item.commentCount }}
        <button class="like-button" @click.stop="toggleFavorite(item)">
          {{ isFavorited(item.id) ? '已收藏' : '收藏' }}
        </button>
      </div>
      
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import '@/styles/articleStyles.less'; // 引入样式文件

export default {
  name: 'ArticlePage',
  data () {
    return {
      articles: [],
      favoriteArticles: [],
      userId: localStorage.getItem('userId')
    }
  },
  async created () {
    try {
      await this.getFavoriteArticles(); // 先获取收藏文章
      const res = await axios.get('http://localhost:8000/getArticles');
      this.articles = res.data; // 确保 API 返回的数据结构正确
      console.log('收藏的文章ID:', this.favoriteArticles);
      console.log('所有文章:', this.articles);
    } catch (error) {
      console.error('获取文章失败:', error);
    }
  },
  methods: {
    getCreatorAvatarUrl(avatarPath) {
      if (avatarPath.startsWith('http://localhost:5000/')) {
        avatarPath = avatarPath.replace('http://localhost:5000/', '');
      }
      if (!avatarPath.startsWith('http')) {
        avatarPath = require(`@/assets/upload/${avatarPath}`);
      }
      return avatarPath;
    },
    async getFavoriteArticles() {
      try {
        const res = await axios.get(`http://localhost:8000/getArticleFavorites/${this.userId}`);
        this.favoriteArticles = res.data.map(favorite => String(favorite.articleId)); // 确保 ID 是字符串类型
        console.log('收藏的文章ID:', this.favoriteArticles);
      } catch (error) {
        console.error('获取收藏文章失败:', error);
      }
    },

    formatDateTime(datetime) {
      if (!datetime) return '';
      const date = new Date(datetime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    isFavorited(articleId) {
      return this.favoriteArticles.includes(String(articleId)); // 确保 ID 是字符串类型
    },
    
    async toggleFavorite(item) {
      console.log(`收藏按钮被点击，文章ID: ${item.id}`);
      console.log(`用户ID: ${this.userId}`);

      if (this.isFavorited(item.id)) {
        // 取消收藏
        try {
          await axios.delete(`http://localhost:8000/delete-favorite?userId=${this.userId}&articleId=${item.id}`);
          this.favoriteArticles = this.favoriteArticles.filter(id => id !== String(item.id));
          alert('取消收藏成功');
        } catch (error) {
          console.error('取消收藏失败:', error);
          alert('取消收藏失败');
        }
      } else {
        // 收藏
        try {
          await axios.post('http://localhost:8000/addArticleFavorite', {
            userId: this.userId,
            articleId: item.id
          });
          this.favoriteArticles.push(String(item.id));
          alert('收藏成功');
        } catch (error) {
          alert('收藏失败');
          console.error('收藏失败:', error);
        }
      }
    }
  }
}
</script>
